#!/usr/bin/env python

import sys
import os
import subprocess
import re
import argparse
import psycopg2
import sblab
import md5

parser = argparse.ArgumentParser(description= """

DEPRECTED: Use fastqfile_to_sblab.py instead.
---------------------------------------------

DESCRIPTION

Upload to table sblab.main.fastqfiles the fastqfile passed as argument.
Library_id is extracted from file name by getting the string from the begining
of the filename till the first dot excluded.

Quality encoding is determined by sblab.get_fastq_encoding().

Note: column service_id is not inserted by default (as it will probably be deprected).

EXAMPLE

TODO:

""", formatter_class= argparse.RawTextHelpFormatter)

parser.add_argument('fastqfile',
                   help='''The fastqfile to upload
                   ''')

parser.add_argument('--library_id', '-i',
                   required= False,
                   default= False,
                   type= str,
                   help='''Assign this library ID instead of extracting it from
the file name.
                   ''')

parser.add_argument('--description', '-d',
                   required= False,
                   default= None,
                   type= str,
                   help='''Optional description to insert in table default None (NULL).
                   ''')

parser.add_argument('--no_commit', '-n',
                   action= 'store_true',
                   help='''Do not commit changes, only show whether insertion is possible.
                   ''')

args = parser.parse_args()

# -----------------------------------------------------------------------------

def sumfile(fobj):
    '''Returns an md5 hash for an object with read() method.'''
    m = md5.new()
    while True:
        d = fobj.read(8096)
        if not d:
            break
        m.update(d)
    return(m.hexdigest())

def md5sum(fname):
    '''Returns an md5 hash for file fname, or stdin if fname is "-".'''
    if fname == '-':
        ret = sumfile(sys.stdin)
    else:
        try:
            f = file(fname, 'rb')
        except:
            return 'Failed to open file'
        ret = sumfile(f)
        f.close()
    return(ret)

# ------------------------------------------------------------------------------

conn= psycopg2.connect(sblab.get_psycopgpass())
cur= conn.cursor()

# Get file encoding
encoding= sblab.get_fastq_encoding(args.fastqfile)
# Get md5
mdsum= md5sum(args.fastqfile)
# Get library_id
if args.library_id:
    library_id= args.library_id
else:
    flist= args.fastqfile.split('.')
    library_id= flist[0]

# Get sequencing platform:
fastqHeader= sblab.IlmnFastqHeader()
fastqHeader.getHeaderFromFile(args.fastqfile)
sequencer_id= fastqHeader.sequencer_id
sequencing_platform= fastqHeader.sequencing_platform
if sequencing_platform is None:
    print('''Warning unknown sequencing platform for sequencer_id %s found in %s.
Sequencer ID will be set to NULL.''' %(sequencer_id, fastqHeader.fastqHeader))
    sequencer_id= None
    
# Check fstqfile exists
sql= 'SELECT * FROM fastqfiles WHERE fastqfile = %(fastqfile)s;'
cur.execute(sql, {'fastqfile': args.fastqfile})
fq= cur.fetchall()
if len(fq) > 0:
    print('\nWarning:\nFastqfile %s found in table fastqfiles. The existing record will be overwritten!\n' %(args.fastqfile))

# Upload
sql= 'DELETE FROM fastqfiles WHERE fastqfile = %(fastqfile)s;'
sql= sql + '\n' + 'INSERT INTO fastqfiles (fastqfile, encoding, library_id, md5sum, description, sequencing_platform, sequencer_id) VALUES (%(fastqfile)s, %(encoding)s, %(library_id)s, %(md5sum)s, %(description)s, %(sequencing_platform)s, %(sequencer_id)s);'
sqldict= {'fastqfile': args.fastqfile, 'encoding': encoding, 'library_id': library_id, 'md5sum': mdsum, 'description': args.description, 'sequencing_platform':sequencing_platform, 'sequencer_id':sequencer_id}
print(cur.mogrify(sql, sqldict))
cur.execute(sql, sqldict)
if not args.no_commit:
    conn.commit()
else:
    print('\nChanges have not been committed\n')
cur.close()
conn.close()

